#!/bin/bash

base_path=$(cd $(dirname $0); pwd)
name=donvan_site

gunicorn=gunicorn
pid_file=$base_path/gunicorn.pid    # -p
access_logfile=$base_path/log/access.log    #--access-logfile
error_logfile=$base_path/log/error.log      #--error-logfile
bind_address='0.0.0.0:8000'     #-b
workers=3   #-w

function start_gunicorn(){
    gunicorn donvan_site.wsgi:application -b $bind_address \
        -w $workers \
        -p $pid_file \
        --access-logfile $access_logfile \
        --error-logfile $error_logfile \
        -D
}


function start(){
    echo -n "$name "
    if check; then
        echo "already started."
    else
        start_gunicorn
        if check; then
            echo "start successfully."
        else
            echo "start failed."
        fi
    fi
}

function stop(){
    echo -n "$name "
    if check; then
        pid=$(cat $pid_file)
        kill $pid
        if check; then
            echo "stop failed."
        else
            echo "stop successfully."
        fi
    else
        echo "already stopped."
    fi
}

function check(){
    sleep 0.1
    if [ -f $pid_file ]; then
        pid=$(cat $pid_file)
        ps axu|grep -q "\<$pid\>"
        return $?
    else
        return 1
    fi
}

case $1 in
    ""|"start")
        start
        ;;
    "stop")
        stop
        ;;
    "status")
        if check; then
            echo "$name is running."
        else
            echo "$name is stopped."
        fi
        ;;
    "restart")
       stop
       start
    ;;
    *)
        echo "usage: $name [start|stop|restart|status]"
        ;;
esac
